package top.continew.admin.controller.api;

import cn.dev33.satoken.annotation.SaIgnore;
import com.feiniaojin.gracefulresponse.api.ExcludeFromGracefulResponse;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.continew.admin.common.util.ShaUtil;

import java.io.IOException;
import java.util.Arrays;

/**
 * @ClassName WxMsgCheckController
 * @Description TODO
 * @Author kellen
 * @Date 2025/7/27 9:37
 */

@SaIgnore
@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping("/wxMsg")
public class WxMsgCheckController {

    // 配置的令牌Token（需与小程序后台配置一致）
    private static final String TOKEN = "IBi4J9sXMqYPuh7JZcoMlrYu6zJ3Pm4U";

    @ExcludeFromGracefulResponse
    @Operation(summary = "微信登录，返回token")
    @RequestMapping(value = "/wxMsgTokenCheck",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public void wxLogin(@RequestParam("signature") String signature,
                        @RequestParam("timestamp") String timestamp,
                        @RequestParam("nonce") String nonce,
                        @RequestParam(value = "echostr",defaultValue = "",required = false) String echostr, HttpServletResponse response) throws IOException {
        log.info("signature:{},timestamp:{},nonce:{},echostr:{}",signature,timestamp,nonce,echostr);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        // 1. 校验签名
        if (checkSignature(signature, timestamp, nonce)) {
            log.info("校验成功返回：echostr {}",echostr);
            // 2. 验证成功返回原始echostr
            response.getWriter().write(echostr);
        }
        // 3. 验证失败返回错误
    }



    /**
     * 微信签名校验算法
     */
    private boolean checkSignature(String signature, String timestamp, String nonce) {
        // 1. 将token、timestamp、nonce按字典序排序
        String[] arr = new String[]{TOKEN, timestamp, nonce};
        Arrays.sort(arr);

        // 2. 拼接字符串
        StringBuilder content = new StringBuilder();
        for (String s : arr) {
            content.append(s);
        }
        // 3. SHA1加密
        String encrypted = ShaUtil.sha1(content.toString());
        // 4. 与signature比对
        return encrypted != null && encrypted.equals(signature);
    }
}
